require('js/lib/require_patch').monkeypatch(this); // android needs this. Apparently there are different contexts

ui = require('js/ui/common/ui');

exports.TestSelectionView = function() {
	var instance = ui.view({
		backgroundColor:'#000'
	});
	
	//Get data for tableview
	var categories = globals.db.listTestCategories();
	for (var i = 0, l = categories.length; i<l; i++) {
		categories[i] = globals.util.objectMerge(categories[i], {
			title: categories[i].name,
	    	height: 50 * globals.deviceFactor,
	    	className: 'top',
	    	hasChild: true
		});
	}

	var categoryTableView = Ti.UI.createTableView({
		data: categories
		});
	var state = {expandedRow: -1,
				childRows: 0,
				highlight: -1,
				urls: globals.util.urls() };
	categoryTableView.addEventListener('click', function(e) {
		Ti.API.debug('Row clicked: ' + e.index + ' Id: ' + e.rowData.id + ' Children: ' + state.childRows + ' Last selected: ' + state.expandedRow);
		if (e.rowData.hasDetail == true) {	
			// Show the test
			showTest(e.rowData.id, categories[state.highlight]);
			state.highlight = -1;
		}
		else {
			state.highlight = e.index < state.expandedRow ? e.index : (e.index - state.childRows < 0 ? 0 : e.index - state.childRows);
			Ti.API.debug('-=-=-= state.highlight: '+state.highlight+' e.index: '+e.index +' state.chiildRows: '+ state.childRows);
			// Acccordian toggle List all tests in the category
			if (state.expandedRow > -1) {
				removeRows(categoryTableView, state.expandedRow, state.childRows);
				state.childRows = 0;				
			}

			if (state.expandedRow != e.index) {
				var loc = state.highlight; 
				state.expandedRow = state.highlight;
				var tests = globals.db.listTests('category = ?', [e.rowData.id]);
				
				for (var i = 0, l=tests.length; i<l; i++) {
					var row = createTestSelector(tests[i]);
					state.childRows++;
					categoryTableView.insertRowAfter(loc++ ,row,{});
				}
			}
			else {
				state.expandedRow = -1;
			}
	
		}
		
		// Show highlighting for the row that was clicked
		if (Titanium.Platform.name != 'android') {
			categoryTableView.selectRow(state.highlight);
		}		
	});

	instance.add(categoryTableView);
	
	instance.filteredViewControl = function() {
		var button = ui.button({
				title:'Filter', 
				backgroundImage: globals.util.urls()['bg_home'], 
				width: 70 * globals.deviceFactor,
				height: 30 * globals.deviceFactor,
				//top:20, 
				left:5
			}, function(e){
			var UtilityWindow = require('js/ui/UtilityWindow');
			var SettingsView = require('js/ui/SettingsView');
			//var filteredResults = globals.db.listPatientTestResultsForResult(globals.patient.id, 'dn');
			var tests = globals.db.listTests();
			var view = Ti.UI.createTableView();
			var filteredData = [];
			for (var i=0, l=tests.length; i<l; i++) {
				var result = globals.db.listPatientTestResults(globals.patient.id, tests[i].id);
				if (result.result.result === 'dn') {
					var category = globals.db.listTestCategories('id = ?', [result.categoryId])[0];
					filteredData.push(createTestSelector(result, category.name + ': '));
				}
			}
			view.data = filteredData;
			var win = new UtilityWindow('Break-out Tests', view, new SettingsView());
			ui.addBackButtonView(win);
			view.addEventListener('click', function(e){
				globals.util.debugDump('Filter click handler', e.row);
				var category = globals.db.listTestCategories('id = ?',[e.rowData.categoryId])[0];
				showTest(e.rowData.id, category);
				win.close();
			});
			
			win.open();
		});
		
		return button;
	}
	
	return instance;

	// Internal functions
	function createRow(name, selected) {
		
		var test = new TestView.TestView({
			title: name,
			selected: selected 
		});
		var testRow = Ti.UI.createTableViewRow({
			className: 'top'
		});
		testRow.add(test);
		
		return testRow;
	}
	
	function createTestSelector(test, namePrefix) {
		category = namePrefix||'';
		Ti.API.debug('Test id: ' + test.id + ' name: ' + test.name + ' category: ' + test.categoryId);
		var icon = state.urls['none']; 
		var pTest = globals.db.listPatientTests('test_id = ? AND patient_id = ? ORDER BY test_date DESC LIMIT 1', 
			[test.id, globals.patient.id]);
		if (pTest[0]) {
			if (pTest[0].result)
				imgIdx = pTest[0].result == 'fn' ? 'stop' : (pTest[0].result == 'dn' ? 'go' : 'yield');
			var icon = state.urls[imgIdx];
			Ti.API.debug('Result is: ' +pTest[0].result+ ' Image index is: ' + imgIdx + ' image is ' + icon);
		}
		return Ti.UI.createTableViewRow({
			className: 'test',
			hasDetail:true,
			indentationLevel:2,
			height: 50 * globals.deviceFactor,
			leftImage: icon,
			id: test.id,
			title: category + test.name,
			categoryId: test.categoryId
		});
	}
	
	function removeRows(tv, start, count) {
		var i = start + count;
		while (i > start) {
			Ti.API.debug("Removing row at: " + i);
			tv.deleteRow(i--,{});
		}
	}
	
	function showTest(testId, category) {
		//show the test view in an Android-specific way
		var test = ui.window('Movement', {
			title:'Test'
		});
		// Get prior test results
		var row = globals.db.listPatientTestResults(globals.patient.id, testId);
		var params = globals.util.objectMerge(row,{
		    	title: category.name + ': ' + row.name,
		    	category: category,
		    	selected: row.result.result
		  	});
		  	
		// Are there more tests?
		rows = globals.db.listTests("id >= ? LIMIT 2", [testId]);
		Ti.API.debug('+++ Retrieved ' + rows.length + ' tests');
		if (rows.length > 1) {
			params.nextTest = rows[1].id;			
		}
		
		var testView = new globals.testView(params);
		test.addChild(testView);
		
		// listen for event requesting to close the test view
		testView.addEventListener('dismiss.test', function(e) {
			Ti.API.debug('++ Dismissing current test. Id: ' + e.id);
			test.close();
			test = null;
			// Refresh parent row
			var rows = globals.db.listTests('id = ?', [e.id]);
			var category = -1;
			if (rows.length > 0) {
				category = rows[0].categoryId;
			}
			
			Ti.API.debug(' +++ Current Category: ' + category + ' expanded row: ' + state.expandedRow);
			var rowId = category - 1;
			if (category - 1 > state.expandedRow) {
				rowId = 1 + state.expandedRow + state.childRows;
			}
			categoryTableView.fireEvent('click', {index: rowId, rowData: {id: category}});
		}); 
		
		// listen for app-level event requesting to go the next test
		testView.addEventListener('next.test', function(e) {
			test.close();
		globals.util.debugDump('Test',e.next);
			var categories = globals.db.listTestCategories('id = (SELECT category FROM tests WHERE id = ?)',[e.next]);
			showTest(e.next, categories[0]);
		});
		
		test.open();
	
	}
	exports.showTest = showTest;

};
